package com.swgk.core.view.recyclerview;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @ClassName HorizontalItemDecoration
 * @Description TODO
 * @Author chongheng.wang
 * @Date 2020/4/28 16:25
 * @Version 1.0
 */
public class VerticalItemDecoration extends RecyclerView.ItemDecoration {
    private int space;//定义2个Item之间的距离
    private boolean setTopAndBottom = false;

    public VerticalItemDecoration(int space, Context mContext) {
        this.space = dip2px(space, mContext);
    }

    public VerticalItemDecoration(int space, Context mContext, boolean setTopAndBottom) {
        this.space = dip2px(space, mContext);
        this.setTopAndBottom = setTopAndBottom;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int totalCount = parent.getAdapter().getItemCount();
        parent.getChildViewHolder(view);
        if (position == 0) {//第一个
            outRect.top = 0;
            if (setTopAndBottom) {
                outRect.top = space;
            }
            outRect.bottom = space / 2;
        } else if (position == totalCount - 1) {//最后一个
            outRect.top = space / 2;
            outRect.bottom = 0;
            if (setTopAndBottom) {
                outRect.bottom = space;
            }
        } else {//中间其它的
            outRect.top = space / 2;
            outRect.bottom = space / 2;
        }
    }

    public int dip2px(float dpValue, Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
